package com.flyan.game.motafx.core.backpack;

import com.almasb.fxgl.entity.Entity;
import com.flyan.game.motafx.config.GameConfig;
import com.flyan.game.motafx.core.enums.EntityTypeEnum;
import com.flyan.game.motafx.core.util.console.ConsoleUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 背包
 *
 * @author flyan
 * @version 1.0
 * @email flyan_by_chenu@sina.com
 * @since 2025/2/5
 */
public class Backpack {

    /**
     * 物品表
     */
    private final Map<EntityTypeEnum, Item> itemTable;

    private final int capacity;

    private int size;

    public Backpack(int capacity) {
        this.capacity = capacity;
        itemTable = new HashMap<>(GameConfig.MAX_BACKPACK_SIZE);
    }

    public Backpack() {
        this(GameConfig.MAX_BACKPACK_SIZE);
    }

    /**
     * 添加物品
     *
     * @param type   物品类型
     * @param amount 数量
     */
    public void addItem(EntityTypeEnum type, Integer amount) {
        if (size + amount > capacity) {
            ConsoleUtils.println("背包已满！当前物品将被丢弃");
            return;
        }

        Item item = itemTable.get(type);
        if (item == null) {
            item = new Item();
            item.type = type;
            item.amount = amount;
            itemTable.put(type, item);
        } else {
            item.amount += amount;
        }

        size += amount;
    }

    /**
     * 移除物品
     *
     * @param type   物品类型
     * @param amount 数量
     */
    public void removeItem(EntityTypeEnum type, Integer amount) {
        Item item = itemTable.get(type);
        if (item == null) {
            return;
        }
        item.amount -= amount;
        if (item.amount <= 0) {
            itemTable.remove(type);
        }

        size -= amount;
    }

    /**
     * 是否有物品
     *
     * @param type   物品类型
     * @param amount 数量
     * @return 是否有物品
     */
    public boolean hasItem(EntityTypeEnum type, Integer amount) {
        Item item = itemTable.get(type);
        if (item == null) {
            return false;
        }
        return item.amount >= amount;
    }

    public int itemAmount(EntityTypeEnum type) {
        Item item = itemTable.get(type);
        if (item == null) {
            return 0;
        }
        return item.amount;
    }

    /**
     * 背包物品
     */
    public static class Item {

        /**
         * 物品类型
         */
        private EntityTypeEnum type;

        /**
         * 数量
         */
        private Integer amount;

    }

}
